package com.example.interviewdemo.demo;

/**
 * @program my-project-model
 * @description:
 * @author: lee
 * @create: 2022/12/29 10:01
 */
public class DeadLockDemo {
    Object object1 = new Object();
    Object object2 = new Object();


    public void methodA()  {
        synchronized (object1) {
            System.out.println("a方法获取锁1" + Thread.currentThread().getName());
            //方法只是阻塞，并不会释放锁
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        synchronized (object2) {
            System.out.println("a方法获取锁2" + Thread.currentThread().getName());
        }
    }

    public void methodB()  {
        synchronized (object2) {
            System.out.println("b方法获取锁2" + Thread.currentThread().getName());
            //方法只是阻塞，并不会释放锁
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        synchronized (object1) {
            System.out.println("b方法获取锁2" + Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) {
        DeadLockDemo deadLockDemo = new DeadLockDemo();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> deadLockDemo.methodA()).start();
            new Thread(()->{deadLockDemo.methodB();}).start();
        }

    }
}
